package com.actor;

import com.actor.networking.NetworkConnection;
import com.actor.networking.NetworkContext;
import com.actor.networking.NetworkMessage;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author Dmitry
 */
public class NetworkQueue {
    private ServerSocket serverSocket;
    private final int port;
    private final LinkedBlockingQueue<NetworkMessage> queue = new LinkedBlockingQueue<>();
    private final NetworkContext networkContext;
    private final Map<Inet4Address, NetworkConnection> connections = new ConcurrentHashMap<>();

    public NetworkQueue(int port, NetworkContext networkContext) throws IOException {
        this.port = port;
        this.networkContext = networkContext;
        init();
    }

    private void init() throws IOException {
        this.serverSocket = new ServerSocket(port);
        Thread serverThread = new Thread() {
            @Override
            public void run() {
                try {
                    Socket socket = serverSocket.accept();
                    processIncomingConnection(socket);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        };

        serverThread.setDaemon(true);
        serverThread.start();
    }

    private void processIncomingConnection(Socket socket) throws IOException {
        NetworkConnection connection = new NetworkConnection(socket, networkContext);
        boolean result = networkContext.getAuthorizationProvider().serverAuthorization(connection);
        if (result == false) {
            connection.close();
            return;
        }

    }
}
